<?php
namespace app\api\controller;

use think\Controller;
use think\Db;

class App extends Controller
{
    // 小程序登录接口
    public function login()
    {
        $code = input('code');
        $nickname = input('nickname', '');
        $avatar = input('avatar', '');
    
        if (!$code) {
            return json(['code' => 0, 'msg' => '缺少code']);
        }
    
        // 微信小程序配置
        $appid = 'wx04e8758082c303db';
        $secret = '727644a75d7e15cfa43844625f98e827';
    
        // 请求微信接口
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $output = curl_exec($ch);
        curl_close($ch);
    
        $res = json_decode($output, true);
    
        if (!isset($res['openid'])) {
            return json(['code' => 0, 'msg' => '微信授权失败', 'data' => $res]);
        }
    
        $openid = $res['openid'];
    
        // 查找用户
        $user = Db::name('sy_user')->where('openid', $openid)->find();
    
        if (!$user) {
            // 注册新用户
            $data = [
                'openid' => $openid,
                'nickname' => $nickname,
                'avatar' => $avatar,
                'create_time' => time()
            ];
            $userId = Db::name('sy_user')->insertGetId($data);
            $user = Db::name('sy_user')->where('id', $userId)->find(); // 重新查一遍带完整数据
        } else {
            // 更新用户信息
            Db::name('sy_user')->where('id', $user['id'])->update([
                'nickname' => $nickname,
                'avatar' => $avatar
            ]);
            $userId = $user['id'];
        }
    
        // 生成 token（此处只是示例）
        $token = md5($openid . time());
    
        return json([
            'code' => 1,
            'msg'  => '登录成功',
            'data' => [
                'user_id'         => $userId,
                'openid'          => $openid,
                'nickname'        => $nickname,
                'avatar'          => $avatar,
                'token'           => $token,
                'name'           => $user['name'],
                'child_name'      => isset($user['child_name']) ? $user['child_name'] : '',
                'child_id_card'   => isset($user['child_id_card']) ? $user['child_id_card'] : '',
                'parent_id_card'  => isset($user['parent_id_card']) ? $user['parent_id_card'] : ''
            ]
        ]);
    }
    
    
    public function bannerList()
{
    $banners = Db::name('sy_banner')
        ->where('status', 1)
        ->order('sort DESC, id DESC')
        ->select();

    if ($banners) {
        // 可根据需要格式化图片链接（如果是相对路径）
        foreach ($banners as &$banner) {
            if (!preg_match('/^https?:\/\//', $banner['image_url'])) {
                $banner['image_url'] = request()->domain() . '/' . ltrim($banner['image_url'], '/');
            }
        }

        return json(['code' => 1, 'data' => $banners]);
    } else {
        return json(['code' => 0, 'msg' => '暂无数据']);
    }
}
    
public function decryptPhone()
{
    $code = input('post.code');
    $encryptedData = input('post.encryptedData');
    $iv = input('post.iv');

    if (!$code || !$encryptedData || !$iv) {
        return json(['code' => 0, 'msg' => '参数不完整']);
    }

    // 小程序配置
    $appId = 'wx04e8758082c303db';
    $appSecret = '727644a75d7e15cfa43844625f98e827';

    // 1. 获取 session_key
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
    $res = file_get_contents($url);
    $resArr = json_decode($res, true);

    if (!isset($resArr['session_key'])) {
        return json(['code' => 0, 'msg' => 'session_key获取失败', 'data' => $resArr]);
    }

    $sessionKey = $resArr['session_key'];

    // 2. 解密数据
    $result = $this->decryptWeixinData($encryptedData, $iv, $sessionKey, $appId);

    if (!$result || !isset($result['phoneNumber'])) {
        return json(['code' => 0, 'msg' => '手机号解密失败']);
    }

    return json(['code' => 1, 'msg' => '获取成功', 'phone' => $result['phoneNumber']]);
}

// 解密函数
private function decryptWeixinData($encryptedData, $iv, $sessionKey, $appid)
{
    if (strlen($sessionKey) != 24) return false;
    $aesKey = base64_decode($sessionKey);
    $aesIV = base64_decode($iv);
    $aesCipher = base64_decode($encryptedData);

    $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, OPENSSL_RAW_DATA, $aesIV);
    $dataObj = json_decode($result, true);

    if ($dataObj == null || $dataObj['watermark']['appid'] != $appid) return false;

    return $dataObj;
}

public function getChildInfo()
{
    $userId = input('get.user_id');

    if (!$userId) {
        return json(['code' => 0, 'msg' => '缺少用户ID']);
    }

    $user = Db::name('sy_user')
        ->field('child_name, child_id_card, child_birthday, child_gender')
        ->where('id', $userId)
        ->find();

    if ($user) {
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $user]);
    } else {
        return json(['code' => 0, 'msg' => '用户不存在或未填写孩子信息']);
    }
}

public function getUserInfo()
{
    $userId = input('get.user_id');

    if (!$userId) {
        return json(['code' => 0, 'msg' => '缺少用户ID']);
    }

    $user = Db::name('sy_user')
        ->where('id', $userId)
        ->find();

    if ($user) {
        $user['user_id'] = $user['id'];

        // 解密身份证号（如果存在）
        if (!empty($user['id_card'])) {
            $user['id_card'] = $this->aesDecrypt($user['id_card']);
        }

        return json(['code' => 1, 'msg' => '获取成功', 'data' => $user]);
    } else {
        return json(['code' => 0, 'msg' => '用户不存在']);
    }
}

// getUserInfo
// 添加到 App 控制器中
public function submitInfo()
{
    $userId = input('post.user_id');

    if (!$userId) {
        return json(['code' => 0, 'msg' => '用户ID缺失']);
    }

    // 检查用户是否存在
    $user = Db::name('sy_user')->where('id', $userId)->find();
    if (!$user) {
        return json(['code' => 0, 'msg' => '用户不存在']);
    }

    // 构建可选更新字段
    $updateData = [];
    $fields = ['name', 'id_card', 'child_id_card', 'child_birthday', 'child_gender', 'phone', 'child_name'];

    foreach ($fields as $field) {
        $value = input('post.' . $field, null);
        if (!is_null($value)) {
            $updateData[$field] = $value;
        }
    }

    if (empty($updateData)) {
        return json(['code' => 0, 'msg' => '无有效更新内容']);
    }

    $result = Db::name('sy_user')->where('id', $userId)->update($updateData);

    if ($result !== false) {
        return json(['code' => 1, 'msg' => '信息提交成功']);
    } else {
        return json(['code' => 0, 'msg' => '信息提交失败']);
    }
}

public function getChildList()
{
    $userId = input('get.user_id');

    if (!$userId) {
        return json(['code' => 0, 'msg' => '用户ID不能为空']);
    }

    // 获取孩子信息列表
    $children = Db::name('sy_child')
        ->where('user_id', $userId)
        ->order('id desc')
        ->select();

    // 解密身份证号
    foreach ($children as &$child) {
        if (!empty($child['child_id_card'])) {
            $child['child_id_card'] = $this->aesDecrypt($child['child_id_card']);
        }
    }

    return json([
        'code' => 1,
        'msg'  => '获取成功',
        'data' => $children
    ]);
}
// 判断姓名是否合法（中文，2-10个字）
private function isValidName($name)
{
    return preg_match('/^[\x{4e00}-\x{9fa5}]{2,10}$/u', $name);
}

public function addChild()
{
    $userId = input('post.user_id');
    $childName = trim(input('post.child_name'));
    $childIdCard = strtoupper(trim(input('post.child_id_card')));
    $childBirthday = input('post.child_birthday');
    $childGender = input('post.child_gender');

    if (!$userId || !$childName || !$childIdCard) {
        return json(['code' => 0, 'msg' => '请填写完整信息']);
    }

    if (!$this->isValidName($childName)) {
        return json(['code' => 0, 'msg' => '请输入2-10位中文姓名']);
    }

    if (!$this->isValidIdCard($childIdCard)) {
        return json(['code' => 0, 'msg' => '身份证格式不正确']);
    }

    $exists = Db::name('sy_child')
        ->where(['user_id' => $userId, 'child_id_card' => $childIdCard])
        ->find();

    if ($exists) {
        return json(['code' => 0, 'msg' => '该孩子信息已存在']);
    }

    $res = Db::name('sy_child')->insert([
        'user_id' => $userId,
        'child_name' => $childName,
        'child_id_card' => $childIdCard,
        'child_birthday' => $childBirthday,
        'child_gender' => $childGender,
        'create_time' => date('Y-m-d H:i:s')
    ]);

    return $res
        ? json(['code' => 1, 'msg' => '添加成功'])
        : json(['code' => 0, 'msg' => '添加失败']);
}


public function updateChild()
{
    $id = input('post.id');
    $childName = trim(input('post.child_name'));
    $childIdCard = strtoupper(trim(input('post.child_id_card')));
    $childBirthday = input('post.child_birthday');
    $childGender = input('post.child_gender');

    if (!$id || !$childName || !$childIdCard) {
        return json(['code' => 0, 'msg' => '缺少必要参数']);
    }

    if (!$this->isValidName($childName)) {
        return json(['code' => 0, 'msg' => '请输入2-10位中文姓名']);
    }

    if (!$this->isValidIdCard($childIdCard)) {
        return json(['code' => 0, 'msg' => '身份证格式不正确']);
    }

    $child = Db::name('sy_child')->where('id', $id)->find();
    if (!$child) {
        return json(['code' => 0, 'msg' => '孩子不存在']);
    }

    $res = Db::name('sy_child')->where('id', $id)->update([
        'child_name' => $childName,
        'child_id_card' => $childIdCard,
        'child_birthday' => $childBirthday,
        'child_gender' => $childGender
    ]);

    return $res !== false
        ? json(['code' => 1, 'msg' => '保存成功'])
        : json(['code' => 0, 'msg' => '保存失败']);
}


public function deleteChild()
{
    $id = input('post.id');
    if (!$id) {
        return json(['code' => 0, 'msg' => '缺少参数']);
    }

    $child = Db::name('sy_child')->where('id', $id)->find();
    if (!$child) {
        return json(['code' => 0, 'msg' => '孩子不存在']);
    }

    $res = Db::name('sy_child')->where('id', $id)->delete();

    return $res
        ? json(['code' => 1, 'msg' => '删除成功'])
        : json(['code' => 0, 'msg' => '删除失败']);
}


public function submitInfoNew()
{
    $userId = input('post.user_id');
    if (!$userId) {
        return json(['code' => 0, 'msg' => '用户ID缺失']);
    }

    // 解密字段函数
    $decrypt = function ($key) {
        $encrypted = input('post.' . $key, '');
        return $encrypted ? $this->aesDecrypt($encrypted) : '';
    };

    // 身份证合法性校验函数
   $isValidIdCard = function ($id) {
        if (!preg_match('/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])' .
            '(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[\dXx]$/', $id)) {
            return false;
        }
    
        // 加权因子
        $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        // 校验码对应规则
        $checkMap = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            $sum += intval($id[$i]) * $factor[$i];
        }
    
        $mod = $sum % 11;
        $expectedCheckCode = $checkMap[$mod];
    
        // 验证最后一位
        return strtoupper($id[17]) === $expectedCheckCode;
    };

    // 自动提取出生日期与性别
    $extractFromIdCard = function ($idCard) {
        $birth = substr($idCard, 6, 8); // YYYYMMDD
        $genderCode = substr($idCard, 16, 1);
        return [
            'birthday' => date('Y-m-d', strtotime($birth)),
            'gender' => $genderCode % 2 === 1 ? '男' : '女'
        ];
    };

    // 检查用户是否存在
    $user = Db::name('sy_user')->where('id', $userId)->find();
    if (!$user) {
        return json(['code' => 0, 'msg' => '用户不存在']);
    }

    // 获取并验证身份证号
    $idCard = $decrypt('id_card');
    if ($idCard && !$isValidIdCard($idCard)) {
        return json(['code' => 0, 'msg' => '联系人身份证格式不正确']);
    }

    // 获取孩子身份证并验证
    $childIdCard = $decrypt('child_id_card');
    if ($childIdCard && !$isValidIdCard($childIdCard)) {
        return json(['code' => 0, 'msg' => '孩子身份证格式不正确']);
    }

    // 更新用户信息
    $userUpdate = [
        'name'     => $decrypt('name'),
        'id_card'  => $idCard ? $this->aesEncrypt($idCard) : '',
        'phone'    => $decrypt('phone')
    ];

    $userUpdate = array_filter($userUpdate); // 移除空字段

    if (!empty($userUpdate)) {
        Db::name('sy_user')->where('id', $userId)->update($userUpdate);
    }

    // 获取并更新孩子信息
    $childName     = $decrypt('child_name');
    $childBirthday = input('post.child_birthday', '');
    $childGender   = input('post.child_gender', '');

    if ($childName && $childIdCard) {
        if (!$childBirthday || !$childGender) {
            $extracted = $extractFromIdCard($childIdCard);
            $childBirthday = $childBirthday ?: $extracted['birthday'];
            $childGender   = $childGender ?: $extracted['gender'];
        }

        $childData = [
            'child_name'     => $childName,
            'child_id_card'  => $this->aesEncrypt($childIdCard),
            'child_birthday' => $childBirthday,
            'child_gender'   => $childGender,
        ];

        $existingChild = Db::name('sy_child')
            ->where(['user_id' => $userId, 'child_id_card' => $this->aesEncrypt($childIdCard)])
            ->find();

        if ($existingChild) {
            Db::name('sy_child')->where('id', $existingChild['id'])->update($childData);
        } else {
            $childData['user_id'] = $userId;
            $childData['create_time'] = date('Y-m-d H:i:s');
            Db::name('sy_child')->insert($childData);
        }
    }

    // 返回用户信息（注意：此处返回的是数据库中已加密的 id_card）
   $newUser = Db::name('sy_user')->where('id', $userId)->find();
$newUser['user_id'] = $newUser['id'];
$newUser['id_card'] = $this->aesDecrypt($newUser['id_card']);
// $newUser['phone'] = $this->aesDecrypt($newUser['phone']);

return json([
    'code' => 1,
    'msg'  => '信息提交成功',
    'data' => $newUser
]);
}


private function aesDecrypt($encrypted)
{
    $key = '1234567890abcdef'; // 与前端 CryptoJS 配置保持一致
    $data = base64_decode($encrypted);
    return openssl_decrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
}

public function submitUserInfo()
{
    $userId = input('post.user_id');
    $name = input('post.name');
    $idCard = input('post.id_card');
    $phone = input('post.phone');
    if (!$userId || !$name || !$idCard || !$phone) {
        return json(['code' => 0, 'msg' => '参数不完整']);
    }

    // 检查用户是否存在
    $user = Db::name('sy_user')->where('id', $userId)->find();
    if (!$user) {
        return json(['code' => 0, 'msg' => '用户不存在']);
    }

    // 更新用户信息
    $updateData = [
        'name' => $name,
        'id_card' => $idCard,
        'phone' => $phone
    ];

    $result = Db::name('sy_user')->where('id', $userId)->update($updateData);

    if ($result !== false) {
        return json(['code' => 1, 'msg' => '信息提交成功']);
    } else {
        return json(['code' => 0, 'msg' => '信息提交失败']);
    }
}


public function submitUserAddress()
{
    $userId = input('post.user_id');
    $province = trim(input('post.province'));
    $city = trim(input('post.city'));
    $district = trim(input('post.district'));
    $detail = trim(input('post.detail'));
        $detail_address= trim(input('post.detail_address'));
     $name = input('post.name');
    $idCard = input('post.id_card');
    $phone = input('post.phone');
    // 参数完整性校验
    // if (!$userId || !$province || !$city || !$district || !$detail) {
    //     return json(['code' => 0, 'msg' => '请填写完整的地址信息']);
    // }

    // 字段格式校验（长度限制可根据实际情况调整）
    // if (mb_strlen($province) > 20 || mb_strlen($city) > 20 || mb_strlen($district) > 20 || mb_strlen($detail) > 100) {
    //     return json(['code' => 0, 'msg' => '地址信息长度超限']);
    // }

    // 用户存在性校验
    $user = Db::name('sy_user')->where('id', $userId)->find();
    if (!$user) {
        return json(['code' => 0, 'msg' => '用户不存在']);
    }

    // 更新地址信息
    $updateData = [
        'name' => $name,
        'id_card' => $idCard,
        'phone' => $phone,
        'province' => $province,
        'city'     => $city,
        'district' => $district,
        'detail_address' => $detail_address
    ];

    $result = Db::name('sy_user')->where('id', $userId)->update($updateData);

    if ($result !== false) {
        return json(['code' => 1, 'msg' => '地址更新成功']);
    } else {
        return json(['code' => 0, 'msg' => '地址更新失败']);
    }
}
public function apiArticleList()
{
    $category = input('get.category/d', 0); // 默认为 0，工作动态
    $limit = input('get.limit/d', 3); // 设置每页返回的新闻数，默认 3 条
    // var_dump($limit);
    // die;
    $articles = Db::name('sy_article')
        ->where('category', $category)
        ->field('id, title, content,desc, create_time,type,link_url')
        ->order('id', 'desc')
        ->limit($limit)
        ->select();

    foreach ($articles as &$article) {
        $article['content'] = mb_substr(strip_tags($article['content']), 0, 50) . '...';
        $article['create_time'] = date('Y-m-d', $article['create_time']);
    }

    return json([
        'code' => 1,
        'msg' => '获取成功',
        'data' => $articles
    ]);
}



public function article_detail()
{
    $id = input('get.id');
    $article = Db::name('sy_article')->where('id', $id)->find();
    if (!$article) {
        return json(['code' => 0, 'msg' => '文章不存在']);
    }

    $article['create_time'] = date('Y-m-d', $article['create_time']);
    return json(['code' => 1, 'msg' => '获取成功', 'data' => $article]);
}


public function categoryList()
{
    $articleCategory = Db::name('sy_course_category')->where('pid',0)->order('sort', 'asc')->select();
    return json(['code' => 1, 'msg' => '获取成功', 'data' => $articleCategory]);
}


public function categoryDetail()
{
    $id = input('get.id');
    $category = Db::name('sy_course_category')->where('id',$id)->find();
    return json(['code' => 1, 'msg' => '获取成功', 'data' => $category]);
}
public function categoryWithCourses()
{
    $id = input('get.id'); // 分类 ID
    if (!$id) {
        return json(['code' => 0, 'msg' => '缺少分类 ID']);
    }

    // 查询分类信息
    $category = Db::name('sy_course_category')->where('id', $id)->find();
    if (!$category) {
        return json(['code' => 0, 'msg' => '分类不存在']);
    }

    // 获取当前分类及其所有子分类的 ID
    $categoryIds = $this->getAllCategoryIds($id);

    // 查询这些分类下的所有课程
    $courses = Db::name('sy_course')
        ->where('status', '<>', 2)
        ->whereIn('category_id', $categoryIds)
        ->field('id, name, expert_name, course_time, desc, location, max_number, title_image, booked')
        ->order('course_time', 'desc')
        ->select();

    // 返回结构
    return json([
        'code' => 1,
        'msg' => '获取成功',
        'data' => [
            'category' => $category,
            'courses' => $courses
        ]
    ]);
}


public function myRatings()
{
    $userId = input('get.user_id');
    if (!$userId) {
        return json(['code' => 0, 'msg' => '缺少用户 ID']);
    }

    $ratings = Db::name('sy_course_rating')
        ->alias('r')
        ->join('sy_course c', 'r.course_id = c.id')
        ->where('r.user_id', $userId)
        ->field([
            'r.id as rating_id',
            'r.content_rating',
            'r.style_rating',
            'r.comment',
            'r.create_time',
            'c.id as course_id',
            'c.name as course_name',
            'c.expert_name',
            'c.course_time',
            'c.location',
            'c.title_image'
        ])
        ->order('r.create_time', 'desc')
        ->select();

    return json([
        'code' => 1,
        'msg' => '获取成功',
        'data' => $ratings
    ]);
}
/**
 * 获取某个分类及其所有子分类的 ID 列表
 */
private function getAllCategoryIds($parentId)
{
    $ids = [$parentId];
    $children = Db::name('sy_course_category')->where('pid', $parentId)->column('id');
    foreach ($children as $childId) {
        $ids = array_merge($ids, $this->getAllCategoryIds($childId));
    }
    return $ids;
}
public function weeklyCourses()
{
    $limit = input('get.limit/d');

    $query = Db::name('sy_course')
        ->where('status', '<>', 2) // 排除已取消的课程
        ->field('id, name, expert_name, course_time, desc, location, max_number, title_image, booked')
        ->orderRaw("
            CASE WHEN course_time > NOW() THEN 0 ELSE 1 END ASC,
            CASE WHEN course_time > NOW() THEN course_time ELSE NULL END ASC,
            CASE WHEN course_time <= NOW() THEN course_time ELSE NULL END DESC
        ");

    if ($limit > 0) {
        $query->limit($limit);
    }

    $courses = $query->select();

    return json([
        'code' => 1,
        'msg' => '获取成功',
        'data' => $courses
    ]);
}


public function courseDetail()
{
    $id = input('get.id');

    if (!$id) {
        return json(['code' => 0, 'msg' => '缺少课程ID']);
    }

    // 查询课程信息
    $course = Db::name('sy_course')->where('id', $id)->find();

    if (!$course) {
        return json(['code' => 0, 'msg' => '课程不存在']);
    }

    // 格式化课程时间
    if (!empty($course['course_time'])) {
        $course['course_time'] = date('Y-m-d H:i', strtotime($course['course_time']));
    }

    // 查询专家信息：支持单个或多个专家ID
    $expertList = [];
    if (!empty($course['expert_id'])) {
        $expertIds = explode(',', $course['expert_id']);
        $expertList = Db::name('sy_expert')->whereIn('id', $expertIds)->select();
    }

    return json([
        'code' => 1,
        'msg'  => '获取成功',
        'data' => [
            'course' => $course,
            'experts' => $expertList
        ]
    ]);
}

public function checkBookingStatus()
{
    $userId = input('get.user_id');
    $courseId = input('get.course_id');

    if (!$userId || !$courseId) {
        return json(['code' => 0, 'msg' => '参数不完整']);
    }

    $exists = Db::name('sy_course_booking')
        ->where(['user_id' => $userId, 'course_id' => $courseId])
        ->find();

    if ($exists) {
        return json(['code' => 1, 'msg' => '已预约', 'booked' => true]);
    } else {
        return json(['code' => 1, 'msg' => '未预约', 'booked' => false]);
    }
}

    // 添加预约记录接口
public function bookCourse()
{
    $userId = input('post.user_id');
    $courseId = input('post.course_id');

    if (!$userId || !$courseId) {
        return json(['code' => 0, 'msg' => '参数不完整']);
    }

    // 检查是否已预约过该课程
    $exists = Db::name('sy_course_booking')
        ->where(['user_id' => $userId, 'course_id' => $courseId])
        ->find();

    if ($exists) {
        return json(['code' => 0, 'msg' => '您已预约过该课程']);
    }
    $user = Db::name('sy_user')->where('id', $userId)->field('phone')->find();
    if (!$user || empty($user['phone'])) {
        return json(['code' => 0, 'msg' => '请去个人中心补充手机号']);
    }
    
    // 获取课程信息，检查是否已满或已结束
    $course = Db::name('sy_course')->where('id', $courseId)->field('booked, max_number, course_time')->find();
    if (!$course) {
        return json(['code' => 0, 'msg' => '课程不存在']);
    }

    // ✅ 判断是否课程人数已满
    if ($course['booked'] >= $course['max_number']) {
        return json(['code' => 0, 'msg' => '该课程已约满']);
    }

    // ✅ 判断是否课程已结束
    if (strtotime($course['course_time']) < time()) {
        return json(['code' => 0, 'msg' => '该课程已结束，无法预约']);
    }

    // 查询孩子信息，筛选出0-1岁的孩子
    $children = Db::name('sy_child')
        ->where('user_id', $userId)
        ->whereNotNull('child_birthday')
        ->select();

    $hasQualifiedChild = false;
    foreach ($children as $child) {
        $birthday = strtotime($child['child_birthday']);
        $ageInMonths = floor((time() - $birthday) / (30 * 86400)); // 近似换算为月数
        if ($ageInMonths >= 0 && $ageInMonths <= 12) {
            $hasQualifiedChild = true;
            break;
        }
    }

    // if (!$hasQualifiedChild) {
    //     return json(['code' => 0, 'msg' => '您暂无0-1岁孩子，无法预约该课程']);
    // }

    // 添加预约记录
    $insertData = [
        'user_id' => $userId,
        'course_id' => $courseId,
        'create_time' => time()
    ];

    $result = Db::name('sy_course_booking')->insert($insertData);

    if ($result) {
        Db::name('sy_course')->where('id', $courseId)->setInc('booked');
        return json(['code' => 1, 'msg' => '预约成功']);
    } else {
        return json(['code' => 0, 'msg' => '预约失败']);
    }
}

public function cancelBooking()
{
    $userId = input('post.user_id');
    $courseId = input('post.course_id');

    if (!$userId || !$courseId) {
        return json(['code' => 0, 'msg' => '参数不完整']);
    }

    // 检查是否有该预约记录
    $exists = Db::name('sy_course_booking')
        ->where(['user_id' => $userId, 'course_id' => $courseId])
        ->find();

    if (!$exists) {
        return json(['code' => 0, 'msg' => '未找到预约记录']);
    }

    // 删除预约记录
    $result = Db::name('sy_course_booking')
        ->where(['user_id' => $userId, 'course_id' => $courseId])
        ->delete();

    if ($result) {
        // 预约人数 -1
        Db::name('sy_course')->where('id', $courseId)->setDec('booked');
        return json(['code' => 1, 'msg' => '取消预约成功']);
    } else {
        return json(['code' => 0, 'msg' => '取消失败']);
    }
}

public function myBookedCourses()
{
    $userId = input('get.user_id');
    if (!$userId) {
        return json(['code' => 0, 'msg' => '缺少用户ID']);
    }

    $courseIds = Db::name('sy_course_booking')
        ->where('user_id', $userId)
        ->column('course_id');

    if (empty($courseIds)) {
        return json(['code' => 1, 'data' => []]);
    }

    $courses = Db::name('sy_course')
        ->alias('c')
        ->join(
            ['bd_sy_course_rating' => 'r'],
            "c.id = r.course_id AND r.user_id = {$userId}",
            'LEFT'
        )
        ->where('c.id', 'in', $courseIds)
        ->field('c.id, c.name, c.location, c.course_time, c.title_image, c.booked, c.max_number, c.replay_video, r.create_time as rating_time')
        ->orderRaw('rating_time DESC, c.course_time ASC')
        ->select();

    foreach ($courses as &$course) {
        $course['is_rated'] = isset($course['rating_time']) && $course['rating_time'] ? 1 : 0;
    }

    return json(['code' => 1, 'data' => $courses]);
}

public function updateRating()
{
    $userId = input('post.user_id');
    $courseId = input('post.course_id');
    $contentRating = input('post.content_rating/d', 0);
    $styleRating = input('post.style_rating/d', 0);
    $comment = input('post.comment', '');

    if (!$userId || !$courseId) {
        return json(['code' => 0, 'msg' => '参数不完整']);
    }

    $exists = Db::name('sy_course_rating')
        ->where(['user_id' => $userId, 'course_id' => $courseId])
        ->find();

    if (!$exists) {
        return json(['code' => 0, 'msg' => '未找到评价记录']);
    }

    $res = Db::name('sy_course_rating')
        ->where(['user_id' => $userId, 'course_id' => $courseId])
        ->update([
            'content_rating' => $contentRating,
            'style_rating' => $styleRating,
            'comment' => $comment,
            // 'update_time' => time()
        ]);

    return $res !== false
        ? json(['code' => 1, 'msg' => '修改成功'])
        : json(['code' => 0, 'msg' => '修改失败']);
}

public function submitRating()
{
    $userId = input('post.user_id');
    $courseId = input('post.course_id');
    $contentRating = input('post.content_rating/d', 0);
    $styleRating = input('post.style_rating/d', 0);
    $comment = input('post.comment', ''); // 新增：评价内容

    if (!$userId || !$courseId) {
        return json(['code' => 0, 'msg' => '参数不完整']);
    }

    // 判断是否已经评价过该课程
    $existing = Db::name('sy_course_rating')
        ->where(['user_id' => $userId, 'course_id' => $courseId])
        ->find();

    if ($existing) {
        return json(['code' => 0, 'msg' => '您已评价过该课程']);
    }

    // 插入评价记录
    $insert = [
        'user_id'        => $userId,
        'course_id'      => $courseId,
        'content_rating' => $contentRating,
        'style_rating'   => $styleRating,
        'comment'        => $comment,       // 加入评价内容
        'create_time'    => time()
    ];

    $res = Db::name('sy_course_rating')->insert($insert);

    if ($res) {
        return json(['code' => 1, 'msg' => '评价成功']);
    } else {
        return json(['code' => 0, 'msg' => '评价失败']);
    }
}

public function getServiceCount()
{
    $userId = input('get.user_id');
    if (!$userId) {
        return json(['code' => 0, 'msg' => '用户ID不能为空']);
    }

    // 获取该用户最后一条服务记录
    $latest = Db::name('sy_jzfw_applications')
        ->where('user_id', $userId)
        ->order('id desc')
        ->find();

    if (!$latest || empty($latest['yl_id'])) {
        return json(['code' => 0, 'msg' => '未找到有效服务记录或yl_id']);
    }

    $elderId = $latest['yl_id'];

    // 获取 token
    $tokenUrl = 'http://180.101.176.137:13306/blade-auth/oauth/token';
    $tokenHeaders = [
        'Authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Content-Type: application/x-www-form-urlencoded',
    ];
    $tokenPostData = http_build_query([
        'grant_type' => 'password',
        'username'   => 'yedj',
        'password'   => '9aa253d2c57f0130d0552df3ccdec34c',
    ]);
    $tokenResponse = $this->httpRequest($tokenUrl, $tokenPostData, $tokenHeaders);
    $tokenData = json_decode($tokenResponse, true);

    if (!isset($tokenData['access_token']) || !$tokenData['access_token']) {
        return json(['code' => 0, 'msg' => 'Token获取失败']);
    }

    // 发起 GET 请求
    $checkUrl = 'http://180.101.176.137:13306/sdcc/tyy/checkElderOrderState?elderId=' . urlencode($elderId);
    
    // var_dump($checkUrl);
    // die;
    $checkHeaders = [
        'Blade-Auth: ' . $tokenData['access_token'],
    ];

    $checkResponse = $this->httpRequest($checkUrl, '', $checkHeaders, 'GET');
    $checkData = json_decode($checkResponse, true);

    if (!isset($checkData['code']) || $checkData['code'] != 200 || !isset($checkData['success']) || !$checkData['success']) {
        return json([
            'code' => 0,
            'msg'  => isset($checkData['msg']) ? $checkData['msg'] : '获取失败'
        ]);
    }

    $data = isset($checkData['data']) ? $checkData['data'] : [];

    return json([
        'code' => 1,
        'msg'  => isset($checkData['msg']) ? $checkData['msg'] : '获取成功',
        'data' => [
            'cstmAmount' => isset($data['cstmAmount']) ? $data['cstmAmount'] : 0,
            'cstmHours'  => isset($data['cstmHours']) ? $data['cstmHours'] : 0
        ]
    ]);
}


public function submitJzfw()
{
    // 接收数据

$data = [
    'name'           => $this->aesDecrypt(input('post.name')),
    'id_card'        => $this->aesDecrypt(input('post.id_card')),
    'phone'          => $this->aesDecrypt(input('post.phone')),
    'address'        => $this->aesDecrypt(input('post.address')),
    'child_name'     => $this->aesDecrypt(input('post.child_name')),
    'child_id_card'  => $this->aesDecrypt(input('post.child_id_card')),
    'birth_cert'     => input('post.birth_cert'), // 图片路径可不加密
    'note'           => $this->aesDecrypt(input('post.note')),
    'create_time'    => time(),
    'create_name'    => input('post.create_name'),
    'user_id'        => input('post.user_id'),
    'service_type'   => 1,
    'district_id'    => input('post.district_id'),
];
    // 校验非空（note 可空）
    $optionalFields = ['note', 'address', 'service_type', 'end_time'];
    
    // var_dump($data);
    // die;
    // 遍历所有字段，排除可选字段，校验其值
    foreach ($data as $key => $value) {
    if (!in_array($key, $optionalFields, true)) {
        if (!isset($value) || (is_string($value) && trim($value) === '')) {
            return json(['code' => 0, 'msg' => "字段 [$key] 缺失或为空"]);
        }
    }
} 
    if (!preg_match('/^\d{17}[\dXx]$/', $data['id_card'])) {
        return json(['code' => 0, 'msg' => '联系人身份证格式不正确']);
    }

    // 🧒 1. 校验孩子是否为 0-1 岁
 
    // if (!preg_match('/^\d{17}[\dXx]$/', $childId)) {
    //     return json(['code' => 0, 'msg' => '孩子身份证格式不正确']);
    // }
    
    
    if (!$this->isValidIdCard($data['id_card'])) {
    return json(['code' => 0, 'msg' => '联系人身份证格式不合法']);
    }
    $childId = $data['child_id_card'];
    if (!$this->isValidIdCard($childId)) {
        return json(['code' => 0, 'msg' => '孩子身份证格式不合法']);
    }
    $birthStr = substr($childId, 6, 8); // 取出生日期
    $birthTime = strtotime($birthStr);
    if (!$birthTime) {
        return json(['code' => 0, 'msg' => '无法解析出生日期']);
    }

    $ageInMonths = floor((time() - $birthTime) / (30 * 24 * 3600));
    if ($ageInMonths < 0 || $ageInMonths > 12) {
        return json([
            'code' => 0,
            'msg' => '您不符合服务要求，本服务仅面向0-1岁孩子的家庭开放'
        ]);
    }
 
    // 📅 当前时间段
    $userId = $data['user_id'];
    $now = time();

    // 月度限制：3 次
    $monthStart = strtotime(date('Y-m-01 00:00:00'));
    $monthEnd = strtotime(date('Y-m-01 00:00:00', strtotime('+1 month')));
    $monthCount = Db::name('sy_jzfw_applications')
        ->where('user_id', $userId)
        ->whereIn('status', [1, 4])
        ->whereBetween('end_time', [$monthStart, $monthEnd])
        ->count();

    if ($monthCount >= 3) {
        return json(['code' => 0, 'msg' => '本月服务次数已达上限（3次）']);
    }

    // 季度限制：9 次
    $month = date('n');
    $season = ceil($month / 3);
    $seasonStartMonth = ($season - 1) * 3 + 1;
    $seasonStart = mktime(0, 0, 0, $seasonStartMonth, 1, date('Y'));
    $seasonEnd = mktime(0, 0, 0, $seasonStartMonth + 3, 1, date('Y'));

    $seasonCount = Db::name('sy_jzfw_applications')
        ->where('user_id', $userId)
        ->whereIn('status', [1, 4])
        ->whereBetween('end_time', [$seasonStart, $seasonEnd])
        ->count();

    if ($seasonCount >= 9) {
        return json(['code' => 0, 'msg' => '本季度服务次数已达上限（9次）']);
    }
    $data['id_card'] = $this->aesEncrypt($data['id_card']);
    $data['child_id_card'] = $this->aesEncrypt($data['child_id_card']);
    // ✅ 插入数据
    $result = Db::name('sy_jzfw_applications')->insertGetId($data);
    if (!$result) {
        return json(['code' => 0, 'msg' => '提交失败']);
    }

    return json(['code' => 1, 'msg' => '提交成功']);
}


private function isValidIdCard($idCard)
{
    if (!preg_match('/^\d{17}[\dXx]$/', $idCard)) return false;

    // 出生日期校验
    $birth = substr($idCard, 6, 8);
    $year  = substr($birth, 0, 4);
    $month = substr($birth, 4, 2);
    $day   = substr($birth, 6, 2);
    if (!checkdate((int)$month, (int)$day, (int)$year)) return false;

    // 校验位算法
    $weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    $validate = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    $sum = 0;
    for ($i = 0; $i < 17; $i++) {
        $sum += intval($idCard[$i]) * $weight[$i];
    }
    $mod = $sum % 11;
    $checkDigit = strtoupper($idCard[17]);

    return $checkDigit === $validate[$mod];
}
// public function submitJzfw()
// {
//     // 接收前端传输的数据
//     $data = [
//         'name'           => input('post.name'),
//         'id_card'        => input('post.idCard'),
//         'phone'          => input('post.phone'),
//         'address'        => input('post.address'),
//         'child_name'     => input('post.childName'),
//         'child_id_card'  => input('post.childIdCard'),
//         'type'           => input('post.type'),
//         'end_time'       => strtotime(input('post.endTime')),
//         'note'           => input('post.note'),
//         'create_time'    => time(),
//         'create_name'    => input('post.create_name'),
//         'user_id'        => input('post.user_id'),
//         'service_type'   => input('post.type'),
//         'district_id'    => input('post.district_id'),
//     ];

//     // 校验非空（note 字段可为空）
//     foreach ($data as $key => $value) {
//         if (empty($value) && $key !== 'note') {
//             return json(['code' => 0, 'msg' => '请填写完整信息']);
//         }
//     }

// //     // 写入数据库
//     $result = Db::name('sy_jzfw_applications')->insertGetId($data);
//     if (!$result) {
//         return json(['code' => 0, 'msg' => '提交失败']);
//     }
//     $tokenUrl = 'http://60.174.231.3:8821/blade-auth/oauth/token';
//     $tokenHeaders = [
//         'Authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0',
//         'Content-Type: application/x-www-form-urlencoded',
//     ];
//     $tokenPostData = http_build_query([
//         'grant_type' => 'password',
//         'username'   => 'yedj',
//         'password'   => '9aa253d2c57f0130d0552df3ccdec34c',
//     ]);
//     $tokenResponse = $this->httpRequest($tokenUrl, $tokenPostData, $tokenHeaders);
//     $tokenData = json_decode($tokenResponse, true);

//     if (empty($tokenData['access_token'])) {
//         return json(['code' => 0, 'msg' => 'Token获取失败']);
//     }

//     // 同步服务对象接口
//     $syncUrl = 'http://60.174.231.3:8821/sdcc/tyy/syncServerObject';
//     $syncHeaders = [
//         'Blade-Auth: ' . $tokenData['access_token'],
//     ];
//     $areaId = Db::name('sy_district')->where(['id' => $data['district_id']])->value('pid');
//     $syncQueryData = http_build_query([
//         'id'           => $result,
//         'name'         => $data['name'],
//         'id_card'      => $data['id_card'],
//         'phone'        => $data['phone'],
//         'address'      => $data['address'],
//         'child_name'   => $data['child_name'],
//         'child_id_card'=> $data['child_id_card'],
//         'areaId'       => $areaId,
//         'stationId'    => $data['district_id'],
//     ]);
    
// //   var_dump(urldecode($syncQueryData));

// //     die;
//  $syncResponse = $this->httpRequest($syncUrl . '?' . $syncQueryData, '', $syncHeaders, 'GET');
// $syncData = json_decode($syncResponse, true);

// // 如果同步失败（如 code 不是 200 或 success 为 false）
// if (empty($syncData) || $syncData['code'] !== 200) {
//     return json([
//         'code' => 0,
//         'msg'  => $syncData['msg'] 
//     ]);
// }

// return json(['code' => 1, 'msg' => '提交并同步成功']);
// }
public function getJzfwRecord()
{
    $userId = input('get.user_id');

    if (!$userId) {
        return json(['code' => 0, 'msg' => '用户ID不能为空']);
    }

    // 查询该用户是否有提交记录
    $record = Db::name('sy_jzfw_applications')
        ->where('user_id', $userId)
        ->order('id', 'desc')
        ->find();

    if ($record) {
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $record]);
    } else {
        return json(['code' => 2, 'msg' => '暂无记录', 'data' => null]);
    }
}

public function getJzfwList()
{
    $userId = input('get.user_id');
    $page = input('get.page', 1);
    $limit = input('get.limit', 10);

    if (!$userId) {
        return json(['code' => 0, 'msg' => '用户ID不能为空']);
    }

    // 查询该用户所有的家政服务申请记录ID
    $regIds = Db::name('sy_jzfw_applications')
        ->where('user_id', $userId)
        ->column('id');

    if (empty($regIds)) {
        return json(['code' => 0, 'msg' => '暂无申请记录']);
    }

    // 构建查询
    $query = Db::name('sy_jzfw_feedback')
        ->whereIn('reg_id', $regIds)
        ->order('create_time', 'desc');

    // 获取总数
    $total = $query->count();

    // 重新构建分页查询（避免 count 后 Query 对象被消耗）
    $list = Db::name('sy_jzfw_feedback')
        ->whereIn('reg_id', $regIds)
        ->order('create_time', 'desc')
        ->page($page, $limit)
        ->select();

    return json([
        'code' => 1,
        'msg'  => '获取成功',
        'data' => [
            'total' => $total,
            'list'  => $list,
            'page'  => $page,
            'limit' => $limit,
        ]
    ]);
}

// 公共 HTTP 请求方法
private function httpRequest($url, $data = null, $headers = [], $method = 'POST')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    if (strtoupper($method) === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
    }

    if (strtoupper($method) === 'GET') {
        curl_setopt($ch, CURLOPT_HTTPGET, true);
    }

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}
    
    public function updateExpiredCourses()
{
    // 当前时间戳
    $now = time();

    // 查询所有未上课且过期的课程
    $courses = Db::name('sy_course')
        ->where('status', 0)
        ->where('course_time', '<', date('Y-m-d H:i:s', $now)) // course_time 是字符串格式
        ->select();

    if (empty($courses)) {
        return json(['code' => 1, 'msg' => '没有需要更新的课程']);
    }

    // 提取要更新的课程ID
    $courseIds = array_column($courses, 'id');

    // 批量更新
    $result = Db::name('sy_course')
        ->where('id', 'in', $courseIds)
        ->update(['status' => 1]);

    if ($result !== false) {
        return json(['code' => 1, 'msg' => '已成功更新' . $result . '条课程状态']);
    } else {
        return json(['code' => 0, 'msg' => '更新失败']);
    }
}
public function submitServiceFeedback()
{
    $data = [
        'reg_id'            => input('post.reg_id'),
        'order_type'        => input('post.order_type', 5), // 默认政府单
        'assign_time'       => input('post.assign_time'),
        'server_start_time' => input('post.server_start_time'),
        'server_end_time'   => input('post.server_end_time'),
        'item_time'         => input('post.item_time'),
        'server_mark'       => input('post.server_mark'),
        'server_star'       => input('post.server_star'),
        'is_cancel'         => input('post.is_cancel', '0'),
        'create_time'       => time()
    ];

    if (empty($data['reg_id'])) {
        return json(['code' => 0, 'msg' => '缺少关联登记ID']);
    }

    // 插入反馈记录
    $result = Db::name('sy_jzfw_feedback')->insert($data);

    if ($result) {
        // 更新登记表状态为“已完成”状态码 4
        // Db::name('sy_jzfw_applications')
        //     ->where('id', $data['reg_id'])
        //     ->update(['status' => 4]);

        return json(['code' => 1, 'msg' => '反馈提交成功']);
    } else {
        return json(['code' => 0, 'msg' => '反馈提交失败']);
    }
}

    
    public function getAllJzfwData()
{
    // 预设秘钥（你可以放在配置文件中）
    $validKey = 'zT4Vq!8KpWd$X3bAeNj7F'; // 这个就是你发给甲方的秘钥

    // 接收秘钥参数
    $accessKey = input('get.access_key');
    // var_dump($accessKey);
    // die;
    // 校验秘钥
    if ($accessKey !== $validKey) {
        return json([
            'code' => 0,
            'msg'  => '无效的秘钥'
        ]);
    }

    // 查询所有家政服务申请数据（可按需限制数量）
    $data = Db::name('sy_jzfw_applications')
        ->order('create_time', 'desc')
        ->select();

    return json([
        'code' => 1,
        'msg'  => '获取成功',
        'data' => $data
    ]);
}

public function getReviewList()
{
    $reviews = Db::name('sy_review')
        ->field('id, course_name, cover_img, video_url, create_time, description, expert_ids')
        ->order('create_time', 'desc')
        ->select();

    foreach ($reviews as &$review) {
        if (!empty($review['expert_ids'])) {
            $ids = explode(',', $review['expert_ids']);
            $expertNames = Db::name('sy_expert')
                ->whereIn('id', $ids)
                ->column('name');
            $review['expert_names'] = implode('，', $expertNames); // 以中文逗号拼接
        } else {
            $review['expert_names'] = '';
        }
        unset($review['expert_ids']); // 如果不需要返回原始ID
    }

    return json(['code' => 1, 'data' => $reviews]);
}

public function getDistrictList()
{
    // 获取所有街道
    $streets = Db::name('sy_district')
        ->where('pid', 0)
        ->field('id, name')
        ->order('id')
        ->select();

    foreach ($streets as &$street) {
        $children = Db::name('sy_district')
            ->where('pid', $street['id'])
            ->field('id, name')
            ->order('id')
            ->select();
        $street['children'] = $children;
    }

    return json(['code' => 1, 'data' => $streets]);
}

public function get_service_subtype_list()
{
    $parentId = 128; // 用 GET 获取参数
    if (!$parentId) {
        return json(['code' => 0, 'msg' => '缺少大类 ID']);
    }

    // 获取 token
    $tokenUrl = 'http://180.101.176.137:13306/blade-auth/oauth/token';
    $tokenHeaders = [
        'Authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Content-Type: application/x-www-form-urlencoded',
    ];
    $tokenPostData = http_build_query([
        'grant_type' => 'password',
        'username'   => 'yedj',
        'password'   => '9aa253d2c57f0130d0552df3ccdec34c',
    ]);
    $tokenResponse = $this->httpRequest($tokenUrl, $tokenPostData, $tokenHeaders);
    $tokenData = json_decode($tokenResponse, true);

    if (empty($tokenData['access_token'])) {
        return json(['code' => 0, 'msg' => 'Token获取失败']);
    }

    // 改成 GET 请求，并将 parentId 作为 URL 参数
    $subtypeUrl = 'http://180.101.176.137:13306/sdcc/tyy/queryServiceItemList?serviceType=' . $parentId;
    $subtypeHeaders = [
        'Blade-Auth: ' . $tokenData['access_token'],
    ];

    $subtypeResponse = $this->httpRequest($subtypeUrl, '', $subtypeHeaders, 'GET');
    $subtypeData = json_decode($subtypeResponse, true);

    if (!isset($subtypeData['code']) || $subtypeData['code'] != 200 || !$subtypeData['success']) {
        $msg = isset($subtypeData['msg']) ? $subtypeData['msg'] : '获取失败';
        return json(['code' => 0, 'msg' => $msg]);
    }

    return json([
        'code' => 1,
        'msg' => '获取成功',
        'data' => $subtypeData['data'],
    ]);
}

public function getConsultPhoneList()
{
    $data = [
        [
            'category' => '产后康复、产后保健、婴幼儿保健课程',
            'phones' => ['0515-81662805', '0515-81662815']
        ],
        [
            'category' => '婴幼儿生活照护课程',
            'phones' => ['0515-68552846']
        ],
        [
            'category' => '家政服务',
            'phones' => ['0515-88848888']
        ],
    ];

    return json(['code' => 1, 'data' => $data]);
}



public function getJzfwTips()
{
    $tips = [
        '1、亭湖区每个0-1岁婴幼儿家庭每个月可申请3个工时（不超过1小时）的家政服务，每个季度可累计使用，季末清零。',
        '2、一次最多申请2个工时，如：1个工时日常清洁，1个工时烹饪膳食；家电清洗一次按3个工时计算。',
        '3、后台每周五统一审核，请耐心等待。资格审查通过后会转家政服务平台为您开通服务账号，三个工作日后即可申请家政服务。如有疑问，请联系81662819（工作日8:30-12:00；14:30-18:00）。'
    ];

    return json(['code' => 1, 'data' => $tips]);
}
public function sendCms()
{
    $accessKeyId = "LTAI5tDJx3FZ11yagMXS9GNm";
    $accessSecret = "7Rsz02wqXazLuR6uyaq3XrF7B1IBoy";

    $params = array(
        "PhoneNumbers" => "18036291231", // 替换为目标手机号
        "SignName" => "亭湖妇幼",
        "TemplateCode" => "SMS_485355497",
        "TemplateParam" => json_encode([
            "date" => "2025-05-07 15:00",
            "name" => "婴幼儿照护",
            "phone" => "81662819"
        ], JSON_UNESCAPED_UNICODE),
    );

    // 系统参数
    $params["RegionId"] = "cn-hangzhou";
    $params["Action"] = "SendSms";
    $params["Version"] = "2017-05-25";
    $params["AccessKeyId"] = $accessKeyId;
    $params["Format"] = "JSON";
    $params["SignatureMethod"] = "HMAC-SHA1";
    $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
    $params["SignatureVersion"] = "1.0";
    $params["SignatureNonce"] = uniqid();

    // 排序并签名
    ksort($params);
    $sortedQueryString = "";
    foreach ($params as $key => $value) {
        $sortedQueryString .= "&" . rawurlencode($key) . "=" . rawurlencode($value);
    }

    $stringToSign = "GET&%2F&" . rawurlencode(substr($sortedQueryString, 1));
    $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessSecret . "&", true));
    $params["Signature"] = $sign;
    // var_dump($params);
    // die;
    // 构建最终 URL
    $url = "https://dysmsapi.aliyuncs.com/?" . http_build_query($params);

    // 发起请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);

    // 返回结果
    $result = json_decode($output, true);
    
    // var_dump($result);
    // die;
    if ($result && isset($result["Code"]) && $result["Code"] === "OK") {
        return json(['code' => 1, 'msg' => '短信发送成功']);
    } else {
        return json(['code' => 0, 'msg' => '发送失败：']);
    }
}

public function submitJzfwService()
{
    $userId = input('post.user_id');
    $serviceId = input('post.service_id');
    $workingHours = input('post.workingHours');

    if (!$userId || !$serviceId || !$workingHours) {
        return json(['code' => 0, 'msg' => '缺少必要参数']);
    }

    // 查找 elderId（来自 sy_jzfw_applications 的 yl_id 字段）
    $latest = Db::name('sy_jzfw_applications')
        ->where('user_id', $userId)
        ->order('id desc')
        ->find();

    if (!$latest || empty($latest['yl_id'])) {
        return json(['code' => 0, 'msg' => '未找到有效服务记录或yl_id']);
    }

    $elderId = $latest['yl_id'];

    // 获取第三方接口 token
    $tokenUrl = 'http://180.101.176.137:13306/blade-auth/oauth/token';
    $tokenHeaders = [
        'Authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Content-Type: application/x-www-form-urlencoded',
    ];
    $tokenPostData = http_build_query([
        'grant_type' => 'password',
        'username'   => 'yedj',
        'password'   => '9aa253d2c57f0130d0552df3ccdec34c',
    ]);
    $tokenResponse = $this->httpRequest($tokenUrl, $tokenPostData, $tokenHeaders);
    $tokenData = json_decode($tokenResponse, true);

    if (empty($tokenData['access_token'])) {
        return json(['code' => 0, 'msg' => 'Token获取失败']);
    }

    // 构造 GET 请求 URL（参数拼接）
    // 将 serviceId 拆分为数组（防止空格或中文逗号）
$serviceIdArr = preg_split('/[\s,，]+/', trim($serviceId));
$itemIdsStr = implode(',', $serviceIdArr);

// 生成对应数量的 1，用英文逗号连接
$itemNumsStr = implode(',', array_fill(0, count($serviceIdArr), 1));
    $query = http_build_query([
        'elderId'   => $elderId,
        'orderCost' => $workingHours,
        'itemNums'  => $itemNumsStr,
        'itemIds'   => $serviceId
    ]);
    
    // var_dump($query);
    // die;
    $requestUrl = 'http://180.101.176.137:13306/sdcc/tyy/pushBabyServiceOrder?' . $query;
    // var_dump($requestUrl);
    // die;
    $headers = [
        'Blade-Auth: ' . $tokenData['access_token']
    ];

    // 发起 GET 请求
    $res = $this->httpRequest($requestUrl, '', $headers, 'GET');
    $resData = json_decode($res, true);

    if (!isset($resData['code']) || $resData['code'] != 200 || !isset($resData['success']) || !$resData['success']) {
        return json([
            'code' => 0,
            'msg'  => isset($resData['msg']) ? $resData['msg'] : '服务提交失败'
        ]);
    }

    return json([
        'code' => 1,
        'msg'  => '提交成功',
        'data' => isset($resData['data']) ? $resData['data'] : []
    ]);
}
private function aesEncrypt($plainText, $key = '1234567890abcdef')
{
    return base64_encode(openssl_encrypt(
        $plainText,
        'AES-128-ECB',
        $key,
        OPENSSL_RAW_DATA
    ));
}


public function encryptAllChildIdCards()
{
    $key = '1234567890abcdef'; // 和前后端统一的 AES 密钥

    // 读取所有未加密的 child_id_card 数据
    $children = Db::name('sy_child')->select();

    $count = 0;

    foreach ($children as $child) {
        $plainIdCard = $child['child_id_card'];

        // 判断是否已经加密（这里假设加密后是 base64 字符串）
        if (preg_match('/^[0-9]{17}[0-9Xx]$/', $plainIdCard)) {
            $encrypted = base64_encode(openssl_encrypt(
                $plainIdCard,
                'AES-128-ECB',
                $key,
                OPENSSL_RAW_DATA
            ));

            Db::name('sy_child')->where('id', $child['id'])->update([
                'child_id_card' => $encrypted
            ]);

            $count++;
        }
    }

    return json(['code' => 1, 'msg' => "加密完成，共更新 {$count} 条记录"]);
}

public function encryptAllUserIdCards()
{
    $key = '1234567890abcdef'; // 请确保这个密钥与前端/解密函数一致

    // 查询所有用户记录
    $users = Db::name('sy_user')->select();
    $count = 0;

    foreach ($users as $user) {
        $id = $user['id'];
        $idCard = $user['id_card'];

        // 判断身份证号是否是明文（未加密）
        if (preg_match('/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])' .
                       '(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[\dXx]$/', $idCard)) {
            $encrypted = base64_encode(openssl_encrypt(
                $idCard,
                'AES-128-ECB',
                $key,
                OPENSSL_RAW_DATA
            ));

            // 更新加密后的身份证号
            Db::name('sy_user')->where('id', $id)->update([
                'id_card' => $encrypted
            ]);

            $count++;
        }
    }

    return json(['code' => 1, 'msg' => "加密完成，共更新 {$count} 条用户记录"]);
}


public function encryptApplicationIdCards()
{
    $list = Db::name('sy_jzfw_applications')->select();

    $count = 0;

    foreach ($list as $row) {
        $updateData = [];

        // 判断并加密联系人身份证
        if (!empty($row['id_card']) && !$this->isEncrypted($row['id_card'])) {
            $updateData['id_card'] = $this->aesEncrypt($row['id_card']);
        }

        // 判断并加密孩子身份证
        if (!empty($row['child_id_card']) && !$this->isEncrypted($row['child_id_card'])) {
            $updateData['child_id_card'] = $this->aesEncrypt($row['child_id_card']);
        }

        // 执行更新
        if (!empty($updateData)) {
            Db::name('sy_jzfw_applications')->where('id', $row['id'])->update($updateData);
            $count++;
        }
    }

    return json(['code' => 1, 'msg' => "加密完成，共更新 {$count} 条记录"]);
}

protected function isEncrypted($str)
{
    // 简单判断是否为密文（你可根据实际密文特征改进）
    return strlen($str) > 20 && preg_match('/^[A-Za-z0-9\+\/=]+$/', $str);
}
}
